<template>
  <div class="list-view">
    <XcTable class="is-list" ref="tableView" :tableKey="$route.path" v-model:page="query.pageIndex"
      v-model:limit="query.pageSize" :pageTotal="total" :config="tableConfig" :state="state" :values="tableData"
      :formRef="queryFormRef" operationWidth="100px" :pagingConfig="{ background: true }" @update="getList">
      <template #default="{ row }">
        <el-link v-if="row.account !== 'admin'" size="small" type="danger" :underline="false"
          @click="onDelete(row)">删除</el-link>
      </template>
      <template #actions>
        <div class="filter-view">
          <el-button type="primary" :icon="Plus" @click="toAdd">新建任务</el-button>
          <XcForm :config="queryFilterConfig" ref="queryFormRef" isQueryFilter @submit="queryFilter"></XcForm>
        </div>
      </template>
      <template #progress="{ row }">
        <el-progress :percentage="Number(row.testProcess)" :color="progressColor(row.testProcess)"></el-progress>
      </template>
    </XcTable>
  </div>
</template>

<script setup lang="ts">
import { useTaskStore } from "../store/taskStore";

defineOptions({
  name: "TaskView",
  components: {}
});

const dataEvent = (data: any) => {
  console.log("子组件收到数据了", data);
}

defineExpose({
  dataEvent
})

// 2. 实例化组合式 store
const taskStore = useTaskStore();

// 验证存储结果
console.log("存储后 Pinia 中的值：", taskStore.sendTaskCmd);

import "@xc-components/xc-form/lib/style.css";
import "@xc-components/xc-table/lib/style.css";

import { ref } from "vue";
import { onMounted } from "vue";
import type { ColumnItem as TableConfig } from "@xc-components/xc-table/types";
import type { ColumnItem as FormConfig, XcFormInstance } from "@xc-components/xc-form/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  getTaskListByCondition,
  deleteTask,
  getTaskSolutions,
  getAllManufacturers,
  routerLinkTestView,
  getMethodDescription
} from "../api/task/index";
import type { TaskItem } from "../api/task/index.d";



const queryFormRef = ref<XcFormInstance>();
const query = ref({ pageIndex: 1, pageSize: 30, manufactureName: "", solutionName: "", taskName: "", testTime: "" });
const state = ref<"loading" | "error" | "">("");
const total = ref(0);
const tableConfig: TableConfig<TaskItem>[] = [
  {
    label: "任务名称1",
    prop: "taskName",
    type: "link",
    onClick: async (row) => {
      console.log("行数据：准备跳转", row);
      await routerLinkTestView("/testView?taskId=" + row.taskId);
    }
  },
  { label: "设备型号", prop: "dutMode" },
  { label: "统计信息", prop: "testProcess", type: "slot", slot: "progress" },
  { label: "解决方案", prop: "solutionName" },
  { label: "设备厂家", prop: "manufacturer" },
  { label: "检测日期", prop: "taskTestTime" }
];
const tableData = ref<TaskItem[]>([]);
const queryFilterConfig = ref<FormConfig[]>([
  { placeholder: "请输入任务名称", prop: "taskName" },
  { placeholder: "请选择解决方案", prop: "solutionName", type: "select", options: [] },
  { placeholder: "请选择设备厂家", prop: "manufactureName", type: "select", options: [] },
  { placeholder: "请选择检测日期", prop: "testTime", type: "date", format: "YYYY/MM/DD", valueFormat: "YYYY/MM/DD" }
]);
onMounted(async () => {

  const descResult = await getMethodDescription();
  console.log("接口方法描述内容", descResult);

  console.log("准备渲染插件页面");
  getList();
  getSolutions();
  getFacturers();

});

/**
 * @description: 获取列表
 */
const getList = async () => {
  state.value = "loading";
  const {
    data: { list, total_Count }
  } = await getTaskListByCondition(query.value);

  console.log("获取的数据", list);

  state.value = "";
  tableData.value = (list || []).map((it: any) => {
    it.testProcess = isNaN(Number(it.testProcess)) ? "0" : it.testProcess;
    return it;
  });
  total.value = total_Count || 0;
};

/**
 * @description: 获取解决方案
 */
const getSolutions = async () => {
  const { data } = await getTaskSolutions({});
  const row = queryFilterConfig.value.find((it) => it.prop === "solutionName");
  if (row) {
    row.options = (data || []).map((it: any) => {
      return { label: it, value: it };
    });
  }
};

/**
 * @description: 获取设备厂家
 */
const getFacturers = async () => {
  const { data } = await getAllManufacturers({});
  const row = queryFilterConfig.value.find((it) => it.prop === "manufactureName");
  if (row) {
    row.options = (data || []).map((it: any) => {
      return { label: it, value: it };
    });
  }
};

/**
 * @description: 筛选
 */
let queryFilter = async ({ value, done }: { value: any; done: () => void }) => {
  query.value.pageIndex = 1;
  query.value = { ...query.value, ...value };
  await getList();
  done?.();
};

/**
 * @description: 删除
 * @param {*} row
 * @return {*}
 */
const onDelete = async (row: TaskItem) => {
  await ElMessageBox({
    title: "提示",
    message: `是否确定删除任务“${row.taskName}”?`,
    type: "warning",
    showCancelButton: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = `执行中...`;
          await deleteTask({ taskId: row.taskId });
          done();
        } catch {
          instance.confirmButtonText = `确定`;
        }
        instance.confirmButtonLoading = false;
      } else {
        done();
      }
    }
  });
  ElMessage.closeAll();
  ElMessage.success(`删除成功`);
  getList();
};
const progressColor = (val: number) => {
  return val < 80 ? (val < 50 ? "#f56c6c" : "#e6a23c") : "";
};
const toAdd = async () => {
  // router.push("/addTask");
  console.log("跳转新建任务");
  await routerLinkTestView("/addTask");
};

</script>

<style lang="scss" scoped>
.list-view {
  padding: 12px;
}
</style>
